class LocalStorageService {

    static get(string) {
        const item = localStorage.getItem(string)
        try {
            return JSON.parse(item)
        } catch (e) {
            return item
        }

    }

    static save(string, val) {
        localStorage.setItem(string, JSON.stringify(val))
    }

    static clear() {
        let l = localStorage.length
        let keyList = []
        for (let i = 0; i < l; i++) {
            let key = localStorage.key(i)
            keyList.push(key)
        }
        keyList.map(key => localStorage.removeItem(key))
    }

    static getSize() {
        let size = 1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length
        return size
    }

    static markGameList(list, data) {
        let key = 'follow_games'
        let follows = this.get(key)
        // console.log(list)
        let obj = {}
        for (let i = 0; i < list.length; i++) {
            let data = list[i]
            let key = data[0]
            let idList = data.slice(1)
            if (follows) {
                let storageList = follows[key]
                let arr = []
                for (let j = 0; j < idList.length; j++) {
                    let id = idList[j]
                    let i = storageList && storageList.findIndex(game => game.matchId === Number(id))
                    if (i > -1) {
                        arr.push(storageList[i])
                    } else {
                        arr.push({matchId: Number(id),})
                    }
                }
                obj[key] = arr
            } else {
                let arr = []
                for (let j = 0; j < idList.length; j++) {
                    let id = idList[j]
                    arr.push({matchId: Number(id),})
                }
                obj[key] = arr
            }
        }
        this.save(key, obj)
    }

    static markOneGame(id, date, gameData) {
        let key = 'follow_games'
        let follows = this.get(key)
        if (follows) {
            let dateFollow = follows[date]
            if (dateFollow) {
                let isFollowed = dateFollow.findIndex(obj => obj.matchId === Number(id))
                if (isFollowed === -1) {
                    follows[date].push(gameData)
                } else {
                    follows[date].splice(isFollowed, 1)
                }
                this.save(key, follows)
            } else {
                follows[date] = [gameData]
                this.save(key, follows)
            }
            // this.setState({gameMarked: !this.state.gameMarked})
        } else {
            let follows = {}
            follows[date] = [gameData]
            this.save(key, follows)
        }
    }

}

export default LocalStorageService
